package com.template.templateuser.auth.serviceauth.util;

import com.template.templateuser.auth.serviceauth.config.TeamplateUserDetails;
import com.template.templateuser.domain.dto.SysUserDTO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.security.Principal;
import java.util.LinkedHashMap;
public class TemplateSecurityContextUtil {
    /**
     * 获取当前用户的userId
     *
     * @return
     */
    public static Long getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof OAuth2Authentication)) {
            return null;
        }
        Object principal = ((OAuth2Authentication) authentication).getUserAuthentication().getPrincipal();

        if (!(principal instanceof TeamplateUserDetails)) {
            return null;
        }
        TeamplateUserDetails teamplateUserDetails = ((TeamplateUserDetails) principal);
        if(teamplateUserDetails!=null){
            SysUserDTO user = teamplateUserDetails.getUser();
            if(user!=null){
                return user.getId();
            }
        }
        return null;
    }

    /**
     * 获取当前用户的用户名
     *
     * @return
     */
    public static String getUserName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null)
            return null;
        return authentication.getName();
    }

}
